<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/17
 * Time: 14:33
 * 将ws面向过程程序修改成面向对象程序
 */

class Ws
{
    const HOST = '0.0.0.0';
    const PORT = 8899;
    public $ws = null;
    public function __construct()
    {
        $this->ws = new swoole_websocket_server(self::HOST, self::PORT);
        /*
        $this->ws->set([
            'enable_static_handler' => true,
            'document_root' => '/data/wwwroot/swoole/data'
        ]);*/

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);

        $this->ws->start();
    }

    /**
     * 监听连接事件
     * @param $ws
     * @param $request
    */
    public function onOpen($ws, $request)
    {
        echo "clinet_{$request->fd} 连接成功!" . PHP_EOL;
    }

    /**
     * 监听消息事件
     * @param $ws
     * @param $frame
    */
    public function onMessage($ws, $frame)
    {
        echo "client:{$frame->fd}-push-message:{$frame->data}" . PHP_EOL;
        $ws->push($frame->fd, "server-push-time:".date("Y-m-d H:i:s"));
    }

    /**
     *  监听关闭事件
     * @param $ws
     * @param $fd
    */
    public function onClose($ws, $fd)
    {
        echo "client {$fd} closed" . PHP_EOL;
    }

}

$ws = new Ws();